// 测试负载均衡功能
const API_BASE = 'http://localhost:3000';

// 模拟多次请求,测试轮询效果
async function testLoadBalancing() {
    console.log('\n========================================');
    console.log('  负载均衡测试');
    console.log('========================================\n');

    // 测试次数
    const testCount = 20;
    const results = {};

    console.log(`发送 ${testCount} 次请求,测试 URL 分配...\n`);

    for (let i = 1; i <= testCount; i++) {
        try {
            const response = await fetch(`${API_BASE}/api/config`);
            const data = await response.json();

            if (data.errcode === 0) {
                const url = data.data.webviewUrl;
                results[url] = (results[url] || 0) + 1;
                
                console.log(`请求 ${i.toString().padStart(2, '0')}: ${url}`);
            }
        } catch (error) {
            console.error(`请求 ${i} 失败:`, error.message);
        }

        // 短暂延迟
        await new Promise(resolve => setTimeout(resolve, 100));
    }

    console.log('\n========================================');
    console.log('  统计结果');
    console.log('========================================\n');

    const total = Object.values(results).reduce((sum, count) => sum + count, 0);

    Object.entries(results).forEach(([url, count]) => {
        const percentage = ((count / total) * 100).toFixed(1);
        const bar = '█'.repeat(Math.round(count / 2));
        console.log(`${url}`);
        console.log(`  次数: ${count}/${total} (${percentage}%)`);
        console.log(`  ${bar}\n`);
    });

    console.log('========================================\n');
}

// 测试不同策略
async function testStrategies() {
    console.log('\n========================================');
    console.log('  测试不同轮询策略');
    console.log('========================================\n');

    const strategies = [
        { name: 'Round Robin (平均轮询)', value: 'round-robin' },
        { name: 'Weighted (权重轮询)', value: 'weighted' },
        { name: 'Random (随机选择)', value: 'random' }
    ];

    for (const strategy of strategies) {
        console.log(`\n测试策略: ${strategy.name}`);
        console.log('----------------------------------------\n');

        // 这里需要先登录获取 token,然后切换策略
        // 简化版本,假设已经配置好
        
        await testLoadBalancing();
        
        // 等待一下
        await new Promise(resolve => setTimeout(resolve, 1000));
    }
}

// 运行测试
testLoadBalancing().catch(console.error);

